package com.test.ayi.test.competablefuture;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Executor;
import java.util.function.Supplier;

public class CFtest9 {
    public static void main(String[] args) throws InterruptedException {
        retryAsync(()->{int i = 1/0; return "success";},3,null);

    }

    public static <T> CompletableFuture<T> retryAsync(
            Supplier<T> task, int maxRetries, Executor executor) {

        CompletableFuture<T> future = new CompletableFuture<>();
        attempt(task, maxRetries, future, executor);
        return future;
    }

    private static <T> void attempt(
            Supplier<T> task, int retriesLeft,
            CompletableFuture<T> future, Executor executor) {
        System.out.println("进入attempt方法");

        CompletableFuture.supplyAsync(task, executor)
                .whenComplete((result, ex) -> {
                    if (ex != null && retriesLeft > 0) {
                        attempt(task, retriesLeft - 1, future, executor);
                    } else if (ex != null) {
                        future.completeExceptionally(ex);
                    } else {
                        future.complete(result);
                    }
                }).join();
    }
}
